<template>
    <el-form :model="form" ref="formRef" label-width="100px" v-loading="formLoading">
        <el-form-item label="品牌名" prop="name">
            <el-input v-model="form.name" clearable />
        </el-form-item>
        <UploadImage label="logo" tag="logo" v-model="form.logo"></UploadImage>
        <el-form-item label="介绍" prop="description">
            <el-input v-model="form.description" clearable />
        </el-form-item>
        <el-form-item label="是否展示" label-width="100px" prop="status">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="检索首字母" label-width="100px" prop="firstLetter">
            <el-input v-model="form.firstLetter" clearable />
        </el-form-item>
        <el-form-item label="排序" label-width="100px" prop="sort">
            <el-input-number :min="0" v-model="form.sort" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts" name="PmsBrandAddOrEdit">
import { ref, reactive, onMounted } from 'vue';
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus';

import { API } from '@/api/mall/pmsBrand';
import type { pmsBrandType } from '@/api/mall/pmsBrand/types';
import { commonGetById, commonCreateOrEdit } from '@/api/common/CommonAPI';
import UploadImage from '@/components/UploadImage.vue';

const props = defineProps(['isEdit', 'id'])
const emit = defineEmits(['success'])

// 确认按钮的loading
const loading = ref(false)
// 加载页面的loading
const formLoading = ref(false)
// 表单回显值
let form = reactive<pmsBrandType>({})
// 用于表单校验
const formRef = ref<FormInstance>()

onMounted(() => {
    if (props.isEdit) {
        load()
    }
})

const load = async () => {
    formLoading.value = true
    try {
        const data = await commonGetById(API.GET_BY_ID, props.id)
        Object.assign(form, data.data)
    } finally {
        formLoading.value = false
    }
}

const submit = async () => {
    await formRef.value?.validate()
    try {
        loading.value = true
        const data = await commonCreateOrEdit(API.CREATE_OR_EDIT, form)
        if (data.code === 200) {
            ElMessage.success(props.isEdit ? '修改成功' : '添加成功')
            emit('success')
        }
    } finally {
        loading.value = false
    }
}
</script>

<style scoped lang="scss"></style>